package com.zqxx.examine.management.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zqxx.examine.common.utils.CustomXWPFDocument;
import com.zqxx.examine.common.utils.Page;
import com.zqxx.examine.management.persistence.ExamPaperMapper;
import com.zqxx.examine.management.persistence.QuestionMapper;
import com.zqxx.examine.model.exam.ExamPaper;
import com.zqxx.examine.model.exam.Paper;
import com.zqxx.examine.model.question.QuestionContent;
import com.zqxx.examine.model.question.QuestionQueryResult;
import com.zqxx.examine.model.question.QuestionStruts;
@Service
public class ExamPaperService {
	 @Autowired
	  private ExamPaperMapper examPaperMapper;
	  @Autowired
	  private QuestionMapper questionMapper;
	  @Autowired
	  private QuestionService questionService;
	  
	  public List<ExamPaper> getExamPaperList(String searchStr, String paperType, Page<ExamPaper> page)
	  {
	    return this.examPaperMapper.getExamPaperList(searchStr, paperType, page);
	  }
	  
	  public void insertExamPaper(ExamPaper examPaper)
	  {
	    this.examPaperMapper.insertExamPaper(examPaper);
	  }
	  
	  @Transactional
	  public void createExamPaper(HashMap<Integer, HashMap<Integer, List<QuestionStruts>>> questionMap, HashMap<Integer, Integer> questionTypeNum, HashMap<Integer, Float> questionTypePoint, HashMap<Integer, Float> knowledgePointRate, ExamPaper examPaper)
	  {
	    HashMap<Integer, String> knowledgeMap = (HashMap)this.questionService.getKnowledgePointMap(0);
	    HashMap<Integer, String> typeMap = (HashMap)this.questionService.getQuestionTypeMap();
	    Paper paper = new Paper(questionMap, questionTypeNum, questionTypePoint, knowledgePointRate, knowledgeMap, typeMap);
	    try
	    {
	      paper.createPaper();
	    }
	    catch (Exception e1)
	    {
	      throw new RuntimeException(e1.getMessage());
	    }
	    try
	    {
	      HashMap<Integer, QuestionStruts> paperQuestionMap = paper.getPaperQuestionMap();
	      
	      Iterator<Integer> it = paperQuestionMap.keySet().iterator();
	      List<Integer> idList = new ArrayList();
	      while (it.hasNext()) {
	        idList.add(it.next());
	      }
	      List<QuestionQueryResult> questionList = this.questionMapper.getQuestionAnalysisListByIdList(idList);
	      for (QuestionQueryResult q : questionList) {
	        q.setQuestionPoint(((Float)questionTypePoint.get(Integer.valueOf(q.getQuestionTypeId()))).floatValue());
	      }
	      Gson gson = new Gson();
	      examPaper.setContent(gson.toJson(questionList));
	      this.examPaperMapper.insertExamPaper(examPaper);
	    }
	    catch (Exception e)
	    {
	      e.printStackTrace();
	      throw new RuntimeException(e.getMessage());
	    }
	  }
	  
	  public ExamPaper getExamPaperById(int examPaperId)
	  {
	    return this.examPaperMapper.getExamPaperById(examPaperId);
	  }
	  
	  public void updateExamPaper(ExamPaper examPaper)
	  {
	    this.examPaperMapper.updateExamPaper(examPaper);
	  }
	  
	  public void deleteExamPaper(int id)
	  {
	    this.examPaperMapper.deleteExamPaper(id);
	  }
	  
	  public List<ExamPaper> getEnabledExamPaperList(String userName, Page<ExamPaper> page)
	  {
	    return this.examPaperMapper.getEnabledExamPaperList(userName, page);
	  }
	  public void generateDoc(ExamPaper examPaper, String path)
			    throws Exception
			  {
			    String basePath = System.getProperty("catalina.base") + ",webapps,";
			    String filePath = basePath + "Management,resources,template,doc_tmp.docx";
			    filePath = filePath.replace(',', File.separatorChar);
			    OPCPackage pack = POIXMLDocument.openPackage(filePath);
			    CustomXWPFDocument doc = new CustomXWPFDocument(pack);
			    Gson gson = new Gson();
			    String content = examPaper.getContent();
			    List<QuestionQueryResult> questionList = (List)gson.fromJson(content, new TypeToken() {}.getType());
			    XWPFParagraph p1 = doc.createParagraph();
			    
			    p1.setAlignment(ParagraphAlignment.CENTER);
			    p1.setVerticalAlignment(TextAlignment.TOP);
			    
			    XWPFRun r1 = p1.createRun();
			    
			    r1.setBold(true);
			    r1.setFontSize(20);
			    
			    r1.setFontFamily("Courier");
			    
			    r1.setTextPosition(40);
			    r1.setText(examPaper.getName());
			    for (QuestionQueryResult question : questionList)
			    {
			    	QuestionContent questionContent = (QuestionContent)gson.fromJson(question.getContent(), QuestionContent.class);
			      
			      XWPFParagraph t = doc.createParagraph();
			      
			      t.setAlignment(ParagraphAlignment.LEFT);
			      t.setVerticalAlignment(TextAlignment.TOP);
			      
			      XWPFRun rt = t.createRun();
			      
			      rt.setBold(false);
			      rt.setFontSize(15);
			      
			      rt.setFontFamily("Courier");
			      
			      rt.setTextPosition(40);
			      rt.setText(questionContent.getTitle() + "(" + question.getQuestionPoint() + "分)");
			      if ((!"".equals(questionContent.getTitleImg())) && (questionContent.getTitleImg() != null))
			      {
			        String titlePicPath = basePath.replace(',', File.separatorChar);
			        File titlePic = new File(titlePicPath + questionContent.getTitleImg());
			        BufferedImage  sourceImg = ImageIO.read(new FileInputStream(titlePic));
			        
			        String ind = doc.addPictureData(new FileInputStream(titlePic), 5);
			        
			        doc.createPicture(doc.getAllPictures().size() - 1, sourceImg
			          .getWidth() / 2, sourceImg.getHeight() / 2);
			        sourceImg.flush();
			      }
			      XWPFParagraph crt = doc.createParagraph();
			      XWPFRun cr = crt.createRun();
			      cr.setText("");
			      if ((question.getQuestionTypeId() == 1) || (question.getQuestionTypeId() == 2) || (question.getQuestionTypeId() == 3)) {
			        for (Map.Entry<String, String> entry : questionContent.getChoiceList().entrySet())
			        {
			          XWPFParagraph c = doc.createParagraph();
			          
			          c.setAlignment(ParagraphAlignment.LEFT);
			          c.setVerticalAlignment(TextAlignment.TOP);
			          
			          XWPFRun rc = c.createRun();
			          
			          rc.setBold(false);
			          rc.setFontSize(15);
			          
			          rc.setFontFamily("Courier");
			          
			          rc.setTextPosition(40);
			          rc.setText((String)entry.getKey() + " " + (String)entry.getValue());
			          if (questionContent.getChoiceImgList().containsKey(entry.getKey()))
			          {
			            String picPath = basePath.replace(',', File.separatorChar) + (String)questionContent.getChoiceImgList().get(entry.getKey());
			            System.out.println(picPath);
			            File picture = new File(picPath);
			            BufferedImage sourceImg = ImageIO.read(new FileInputStream(picture));
			            
			            String ind = doc.addPictureData(new FileInputStream(picture), 5);
			            
			            doc.createPicture(doc.getAllPictures().size() - 1, sourceImg
			              .getWidth() / 2, sourceImg.getHeight() / 2);
			            sourceImg.flush();
			          }
			          XWPFParagraph crta = doc.createParagraph();
			          XWPFRun cra = crta.createRun();
			          cra.setText("");
			        }
			      }
			    }
			    try
			    {
			      QuestionContent questionContent;
			      BufferedImage sourceImg;
			      File f = new File(path);
			      if (!f.exists()) {
			        f.mkdirs();
			      }
			      FileOutputStream out = new FileOutputStream(path + File.separatorChar + examPaper.getName() + ".docx");
			      doc.write(out);
			      out.close();
			      System.out.println("success");
			    }
			    catch (FileNotFoundException e)
			    {
			      e.printStackTrace();
			    }
			    catch (IOException e)
			    {
			      e.printStackTrace();
			    }
			  } 
	  
}
